<template>
  <div class="upload-container">
    <el-upload
        class="upload-demo"
        action="/api/upload/image"
        :on-success="handleSuccess"
        :before-upload="beforeUpload"
        :show-file-list="false"
    >
      <el-button size="small" type="primary">点击上传</el-button>
    </el-upload>
    <div v-if="imageUrl" class="image-preview">
      <img :src="imageUrl" alt="Uploaded Image" />
    </div>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus';
import { ref } from 'vue'

const imageUrl = ref(null);

const handleSuccess = (response, file) => {
  console.log('上传成功:', response);
  if(response.code === 200) { // 假设后端返回包含code字段
    ElMessage.success('文件上传成功');
    imageUrl.value = `/api/mg/${response.data.fileName || file.name}`;
  } else {
    ElMessage.error(response.message || '上传失败');
  }
};

const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return false;
  }
  return true;
};
</script>

<style scoped>
.upload-container {
  padding: 20px;
  text-align: center;
}
.image-preview {
  margin-top: 20px;
}
.image-preview img {
  max-width: 100%;
  max-height: 300px;
  border: 1px solid #eee;
  border-radius: 4px;
}
</style>